#include "system.h"
#include "lpc213x.h"


#define PLOCK 0x400
#define SLOW_IO

void feed(void) {
	PLLFEED = 0xAA;
	PLLFEED = 0x55;
}

void system_Init(void) {

	// Setting Multiplier and Divider values
	// PLLCFG (0-4) = M-1 = 5 = 0b00101
	// PLLCFG (5-6) = P = Fcco / (2xCclk) = 2

	PLLCFG = 0x25;
	feed();

	// Enabling the PLL */
	PLLCON = 0x1;
	feed();

	// Wait for the PLL to lock to set frequency
	while (!(PLLSTAT & PLOCK))
		;

	// Connect the PLL as the clock source
	PLLCON = 0x3;
	feed();

	// Enabling MAM and setting number of clocks used for Flash memory fetch (4 cclks in this case)
	MAMCR = 0x0;
	MAMTIM = 0x3;
	MAMCR = 0x2;

	// Setting peripheral Clock (pclk) to System Clock (cclk)
	VPBDIV = 0x1;

#ifdef SLOW_IO
#elif FAST_IO
	// ENABLE FIO //on both ports!
	SCS |= 3;
#endif
}


void system_HardwareSPI1Init() {

}

//init SPI Bus for LCD - 9bits - HiFreq - SPI1 Interfase
void system_SoftwareSPI1Init() {
	/*  	PINSEL0 |= 0x00001500; // SCK0 MISO0 and MOSI0 enabled, SSEL0 ad GPIO
	 S0SPCR   = 0x0924; // Master - 9bits - Mode 3
	 S0SPCCR  = 0x0C; // Fastest Speed
	 */
#ifdef USE_HARD_SPI_FOR_LCD
	// PCLK = 60MHz
	IODIR0 |= (LCD_MOSI | LCD_SCK | LCD_CS | LCD_RESET);

	// reset Pin-Functions
	SPI_PINSEL &= ~( (3<<SPI_SCK_FUNCBIT) | (3<<SPI_MISO_FUNCBIT) |
			(3<<SPI_MOSI_FUNCBIT) | (3<<SPI_SS_FUNCBIT) );

	// set Pin Functions
	SPI_PINSEL |= ((2<<SPI_SCK_FUNCBIT) | (0<<SPI_MISO_FUNCBIT) |
			(2<<SPI_MOSI_FUNCBIT) | (0<<SPI_SS_FUNCBIT));

	SSPCR1 = 0; //disable

	// CPOL = 0 CPHA = 0 9bits SPI
	SSPCR0 = ((SPI_DATABITS-1)<<0) | (0<<SPI_CPOL) | (16<<SPI_SCR);

	SSPCR1 |= (1<<SSP_SSE);

	SSPCPSR = 32;

	IOSET0 = LCD_CS;
	IOCLR0 = LCD_RESET;

#else
	IODIR0 |= (LCD_MOSI | LCD_SCK | LCD_CS | LCD_RESET);
	IOCLR0 = LCD_SCK;
	IOCLR0 = LCD_MOSI;
	IOSET0 = LCD_CS;
	IOCLR0 = LCD_RESET;
#endif
}
